package com.creditease.shield.flow.boot;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.EnableTransactionManagement;


/**
 * @author jpa配置数据源
 */

@Configuration
@EnableTransactionManagement //事务注解
public class DatabaseConfiguration {

    @Autowired
    private DruidConfigEntity druidConfigEntity;

    @Bean
    @Primary
    public DruidDataSource createDataSource() {

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(druidConfigEntity.getDriverClassName());
        dataSource.setUrl(druidConfigEntity.getUrl());
        dataSource.setUsername(druidConfigEntity.getUsername());
        dataSource.setPassword(druidConfigEntity.getPassword());
        //配置初始化大小、最小、最大
        dataSource.setInitialSize(Integer.valueOf(druidConfigEntity.getInitialSize()));
        dataSource.setMinIdle(Integer.valueOf(druidConfigEntity.getMinIdle()));
        dataSource.setMaxActive(Integer.valueOf(druidConfigEntity.getMaxActive()));
        //配置获取连接等待超时的时间
        dataSource.setMaxWait(Long.valueOf(druidConfigEntity.getMaxWait()));

        dataSource.setValidationQuery("SELECT 'x'");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);

        //打开PSCache，并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);

        //超过时间限制是否回收
        dataSource.setRemoveAbandoned(true);
        //超时时间；单位为秒
        dataSource.setRemoveAbandonedTimeout(30);
        //关闭abanded连接时输出错误日志
        dataSource.setLogAbandoned(true);

        //在一定毫秒数内关闭空闲连接
        dataSource.setTimeBetweenConnectErrorMillis(Long.valueOf(druidConfigEntity.getTimeBetweenEvictionRunsMillis()));
        dataSource.setMinEvictableIdleTimeMillis(Long.valueOf(druidConfigEntity.getMinEvictableIdleTimeMillis()));

        return dataSource;
    }
    
}
